package com.coolxi.controller;

import com.coolxi.dao.FlowerMapper;
import com.coolxi.entity.Flower;
import com.coolxi.entity.Pager;
import com.coolxi.service.FlowerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Eoly on 2017/6/12.
 */
@Controller
@RequestMapping("/")
public class PageController {
    @Autowired
    FlowerService flowerService;
    @Autowired
    FlowerMapper flowerMapper;

    @RequestMapping("/flower/add.html")
    public String addPage(Model model) {
        model.addAttribute("flower", new Flower());
        return "flower/addPage";
    }

    @RequestMapping("/user/login.html")
    public String login(Model model) {
        return "flower/login";
    }

    @RequestMapping("/flower/edit/{id}.html")
    public String editPage(Model model, @PathVariable Integer id, HttpServletRequest request) {
        Flower flower = flowerMapper.selectByPrimaryKey(id);
        if (flower==null){
            throw new RuntimeException("该花不存在");
        }
        if (request.getAttribute("flower")==null){
            model.addAttribute("flower", flower);
        }else {
            model.addAttribute("flowerImg", flower.getFlowerImgAddress());
        }
        return "flower/modify";
    }

    @RequestMapping("/flower/home.html")
            public String homePage(
            Model model,
            @RequestParam(value = "pager.offset", required = false) Integer offset
    ) {
        if (offset == null) {
            offset = 0;
        }
        Integer pageSize = 8;
        List<Flower> flowers = flowerService.findFlowers(offset, pageSize);
        Integer flowerSize = flowerMapper.selectFlowerCount();
        Pager<Flower> pager = new Pager<Flower>(flowers, pageSize, flowerSize, offset);
        pager.setUrl("home.html");
        model.addAttribute("pager", pager);
        return "flower/home";
    }
}
